
import esprima
import json

# JavaScript 代码示例
js_code = """
function calculateSum(a, b) {
    const result = a + b;
    return result;
}

class Calculator {
    constructor(initialValue = 0) {
        this.value = initialValue;
    }
    
    add(number) {
        this.value += number;
        return this.value;
    }
    
    static multiply(x, y) {
        return x * y;
    }
}

const calc = new Calculator(10);
const sum = calculateSum(5, 3);
let total = calc.add(sum);
"""

# 解析 JavaScript 代码
ast = esprima.parseScript(js_code)

def analyze_js_code(ast):
    """分析 JavaScript 代码结构"""
    functions = []
    classes = []
    variables = []
    
    def traverse(node):
        if node.type == 'FunctionDeclaration':
            functions.append({
                'name': node.id.name,
                'params': [param.name for param in node.params],
                'type': 'function'
            })
        elif node.type == 'ClassDeclaration':
            class_info = {
                'name': node.id.name,
                'methods': []
            }
            # 遍历类的方法
            for item in node.body.body:
                if item.type == 'MethodDefinition':
                    class_info['methods'].append({
                        'name': item.key.name,
                        'kind': item.kind,
                        'static': item.static
                    })
            classes.append(class_info)
        elif node.type == 'VariableDeclaration':
            for declarator in node.declarations:
                variables.append({
                    'name': declarator.id.name,
                    'kind': node.kind
                })
        
        # 递归遍历子节点
        for key, value in node.__dict__.items():
            if isinstance(value, list):
                for item in value:
                    if hasattr(item, 'type'):
                        traverse(item)
            elif hasattr(value, 'type'):
                traverse(value)
    
    traverse(ast)
    return {
        'functions': functions,
        'classes': classes,
        'variables': variables
    }

analysis = analyze_js_code(ast)
print(json.dumps(analysis, indent=2))
